package dao

import (
	"disk/service/user/dao/service"
	"disk/utils/mysql"
	"gorm.io/gorm"
	"log"
	"time"
)

// RecordPasswordWrong 记录用户密码错误次数（支持自动封禁）
func RecordPasswordWrong(userData mysql.UserList, tries uint) bool {
	// 方式一 分布式锁 强一致性
	lock := service.GetRedLock(userData.Name)
	// 尝试获取锁
	if err := lock.Lock(); err != nil {
		log.Println("获取锁失败:", err)
		return false
	}
	defer lock.Unlock()           // 函数结束时释放锁
	go service.ContinueLock(lock) // 启动一个协程来定期检查并延时锁

	db := service.Database.Session(&gorm.Session{NewDB: true})
	userData.PasswordTry = tries
	if userData.PasswordTry >= 10 {
		userData.LockedUntil = time.Now().Add(time.Hour)
		userData.PasswordTry = 0
	}
	service.ClearNameRedisCache(userData.Name)
	db.Save(&userData)
	return true
}

// SetUserStatus 设置用户状态（如“正常”/“禁用”）
func SetUserStatus(userData mysql.UserList, status string) bool {
	// 方式一 分布式锁 强一致性
	lock := service.GetRedLock(userData.Name)
	// 尝试获取锁
	if err := lock.Lock(); err != nil {
		log.Println("获取锁失败:", err)
		return false
	}
	defer lock.Unlock()           // 函数结束时释放锁
	go service.ContinueLock(lock) // 启动一个协程来定期检查并延时锁

	db := service.Database.Session(&gorm.Session{NewDB: true})
	userData.Status = status
	service.ClearNameRedisCache(userData.Name)
	db.Save(&userData)
	return true
}

// SetUserPwd 设置用户密码（带弱一致性的缓存更新）
func SetUserPwd(userData mysql.UserList, newPwd string) bool {
	db := service.Database.Session(&gorm.Session{NewDB: true})
	userData.Password = newPwd
	// 方式二：双删，弱一致性
	go service.ClearNameRedisCache(userData.Name)
	db.Save(&userData)
	go service.SendMsgToMq(userData.Name, time.Now().Add(1000*time.Millisecond))
	return true
}
